package com.faceCaptor.main;

import com.alibaba.fastjson.JSONObject;
import com.faceCaptor.util.HttpUtil;
import com.faceCaptor.util.JsonUtil;
import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Properties;

/**
 * ClassName: UpdateDialog <br/>
 * Description: <br/>
 * date: 2019/11/3 20:33<br/>
 *
 * @author geyee<br />
 */
public class UpdateDialog extends Dialog {

    private Logger logger = Logger.getLogger(UpdateDialog.class);

    private String version;
    private CLabel label;
    private ProgressBar progressBar;
    public static void main(String[] args) {
        UpdateDialog updateDialog = new UpdateDialog(null);
        updateDialog.open();
    }
    @Override
    protected void configureShell(Shell newShell) {
        super.configureShell(newShell);
        newShell.setText("软件更新");
    }

    protected UpdateDialog(Shell parentShell) {
        super(parentShell);
    }

//    @Override
//    protected int getShellStyle() {
//        return SWT.TITLE | SWT.CLOSE | SWT.MIN;
//    }
    @Override
    protected Control createDialogArea(Composite parent) {
        Composite container = (Composite) super.createDialogArea(parent);
        container.setLayout(new GridLayout());
        label = new CLabel(container,SWT.None);
        GridData data = new GridData(GridData.FILL_BOTH);
        label.setAlignment(SWT.CENTER);
        label.setLayoutData(data);
        Properties properties = new Properties();
        InputStream in = getClass().getResourceAsStream("/application.properties");
        try {
            properties.load(in);
            this.version = properties.getProperty("version");
        } catch (IOException e) {
            logger.error("加载application.properties失败");
        }
        label.setText("当前版本：" + this.version);
        GridData gridData = new GridData(GridData.FILL_BOTH);
        gridData.verticalAlignment = 2;
        progressBar = new ProgressBar(container, SWT.None);
        progressBar.setMinimum(0);
        progressBar.setMaximum(100);
        progressBar.setLayoutData(gridData);
        progressBar.setVisible(false);
        Color color = Display.getCurrent().getSystemColor(SWT.BACKGROUND);
        container.setForeground(color);

        return container;
    }

    @Override
    protected Point getInitialSize() {
        return new Point(500, 300);
    }

    @Override
    protected Point getInitialLocation(Point initialSize){
        Point location = new Point(this.getParentShell().getLocation().x
                + 100, this.getParentShell().getLocation().y
                + 100);
        return location;
//        return new Point(100,100);

    }
    @Override
    protected void createButtonsForButtonBar(Composite parent) {
        Button updateButton = createButton(parent, IDialogConstants.YES_ID, "检查更新", false);
        updateButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String result = HttpUtil.sendGetRequest(HttpUtil.HOST + HttpUtil.CHECK_UPDATA + version);
                JSONObject jsonObject = JsonUtil.toJsonObject(result, "data");
                String text = label.getText();
                if (jsonObject == null) {
                    label.setText(text + "\n\n当前版本已经是最新版");
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    label.setText(text + "\n\n最新版本：" + jsonObject.getString("version") +
                            "\n更新时间：" + sdf.format(jsonObject.getDate("createTime")) +
                            "\n更新内容：" + jsonObject.getString("description"));
                }
                if (jsonObject != null) {
                    progressBar.setVisible(true);
                    updateButton.setEnabled(false);
                    String downloadUrl = jsonObject.getString("downloadUrl");
                    String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1);
                    HttpUtil.download(jsonObject.getString("downloadUrl"), fileName, progress -> {

                        Display.getDefault().syncExec(new Runnable() {
                            @Override
                            public void run() {
                                if(!HttpUtil.isCancel && !progressBar.isDisposed()) {
                                    try {
                                        progressBar.setSelection(progress);
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }
                        });
                    });
                }
            }
        });
        Button closeButton = createButton(parent, IDialogConstants.OK_ID, "关闭", true);
        closeButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                HttpUtil.cancelDownload();
            }
        });
        GridData gridData = (GridData) parent.getLayoutData();
        gridData.horizontalAlignment = SWT.CENTER;
    }
}
